//
//  CommentViewController.m
//  B
//
//  Created by lanou on 16/5/12.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentCell.h"
#import "CommentModel.h"
#import "BaseTableViewCell.h"
#import "TableViewCellFactory.h"
#import "SVProgressHUD.h"


#define kGETCOMMENTURL @"http://app.dunkhome.com/v2/news/"
#define kSENDCOMMENTURL @"http://app.dunkhome.com/v2/news/28292/comments"
// http: //app.dunkhome.com/v2/news/28265/comments

@interface CommentViewController ()<UITableViewDataSource, UITableViewDelegate>

// 显示所有的评论
@property (nonatomic, strong) UITableView *commentTableView;
@property (nonatomic, strong) NSMutableArray *allCommentArray;
// textView,发送按钮所在的view
@property (nonatomic, strong) UIView *backView;
// 输入框
@property (nonatomic, strong) UITextView *textView;
// 评论内容数组
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation CommentViewController
{
    // 初始化的原始大小
    CGRect originFrame;
    // tableView初始化大小
    CGRect originTableViewFrame;
    // 网址
    NSString *commentURL;
}

-(NSMutableArray *)allCommentArray
{
    if (!_allCommentArray) {
        _allCommentArray = [NSMutableArray array];
    }
    return _allCommentArray;
}

-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

-(void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    commentURL = [[NSString alloc]init];
    // Do any additional setup after loading the view.
    NSString *str = [self.ID stringByAppendingString:@"/comments"];
    commentURL = [kGETCOMMENTURL stringByAppendingString:str];
    
    self.commentTableView.estimatedRowHeight = 1000;
    self.commentTableView.rowHeight = UITableViewAutomaticDimension;
    
    [self requestData];
    self.view.backgroundColor = [UIColor cyanColor];
    [self createSubviews];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 使用消息机制，监听将要显示键盘修改UI
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    // 监听键盘消失
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
}

// 键盘显示 -- tableView、backView向上拉伸
-(void)keyboardWillShow:(NSNotification *)note
{
    NSDictionary *userInfo = note.userInfo;
    // 取出键盘的大小
    NSValue *frameValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = frameValue.CGRectValue;
    // 取出键盘动画时长
    NSNumber *time = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    // tableView向上延长键盘高度
    CGRect originTB = originTableViewFrame;
    originTB.origin.y -= keyboardFrame.size.height;
    // backView向上延长键盘的高度
    CGRect originBF = originFrame;
    originBF.origin.y -= keyboardFrame.size.height;
    // 设置动画
    [UIView animateWithDuration:time.doubleValue animations:^{
        self.commentTableView.frame = originTB;
        self.backView.frame = originBF;
    }];
}

// 键盘消失 -- tableView、backView回收
-(void)keyboardWillHide
{
    [UIView animateWithDuration:0.25 animations:^{
        self.backView.frame = originFrame;
    }];
}

#pragma mark - 创建子视图
-(void)createSubviews
{
    self.commentTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 100 - 64) style:UITableViewStylePlain];
    // 原始tableView的大小
    originTableViewFrame = self.commentTableView.frame;
    // 注册cell
    [self.commentTableView registerNib:[UINib nibWithNibName:@"CommentCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([CommentModel class])];
    self.commentTableView.delegate = self;
    self.commentTableView.dataSource = self;
    [self.view addSubview:self.commentTableView];
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 100, ScreenWidth, 100)];
    self.backView.backgroundColor = [UIColor blackColor];
    // 设置backView的位置
    originFrame = self.backView.frame;
    
    [self.view addSubview:self.backView];
    UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeSystem];
    sendButton.frame = CGRectMake(ScreenWidth - 55, 5, 55, 80);
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(sendMessage:) forControlEvents:UIControlEventTouchUpInside];
    [sendButton setTintColor:[UIColor whiteColor]];
    sendButton.backgroundColor = [UIColor colorWithRed:0.892 green:0.721 blue:1.000 alpha:1.000];
    
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(5, 5, ScreenWidth - 65, 30)];
    self.textView.backgroundColor = [UIColor greenColor];
    
    [self.backView addSubview:sendButton];
    [self.backView addSubview:self.textView];
}

#pragma mark - 点击方法
-(void)sendMessage:(UIButton *)button
{
    self.commentTableView.frame = originTableViewFrame;
    NSLog(@"发送消息");
    if (self.textView.text == nil) {
        NSLog(@"发送消息为空");
    } else {
        [self.textView resignFirstResponder];
        self.textView.text = nil;
        [self sendComment];
    }
}

#pragma mark - 获取评论
-(void)requestData
{
    self.dataSource = nil;
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:commentURL  parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        [SVProgressHUD showWithStatus:@"waiting"];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        for (NSDictionary *dict in responseObject) {
            
            CommentModel *model = [CommentModel new];
            model.formatted_published_at = dict[@"formatted_published_at"];
            model.content = dict[@"content"];
            [model setValuesForKeysWithDictionary:dict[@"creator"]];
            [self.dataSource addObject:model];
        }
        [SVProgressHUD dismiss];
        [self.commentTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);        
    }];
}

/*
 client=2&content=%E6%81%A9
*/
#pragma mark - 发表评论
-(void)sendComment
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session POST:kSENDCOMMENTURL parameters:@{@"client":@2, @"content":self.textView.text} progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"aaaaaaaaaaaa");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"bbbbbbbbbbbbb");
        id sendData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"-------------%@", sendData);
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"cccccccccccccc = %@", error);
    }];
}

#pragma mark - 代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentModel *model = self.dataSource[indexPath.row];
    BaseTableViewCell *cell = [TableViewCellFactory cellWithModelClass:[model class] tableView:tableView index:indexPath];
    [cell setDataWithModel:model];
    return cell;
}

//
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.textView resignFirstResponder];
    self.commentTableView.frame = originTableViewFrame;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
